package com.funsport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funsport.entity.Club;
import com.funsport.entity.ClubMember;
import com.funsport.exception.BusinessException;
import com.funsport.mapper.ClubMemberMapper;
import com.funsport.service.IClubMemberService;
import com.funsport.service.IClubService;
import com.funsport.service.IPointsService;
import com.funsport.service.INotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ClubMember Service实现
 */
@Slf4j
@Service
public class ClubMemberServiceImpl extends ServiceImpl<ClubMemberMapper, ClubMember> implements IClubMemberService {

    @Autowired
    private IClubService clubService;
    
    @Autowired
    @Lazy
    private IPointsService pointsService;
    
    @Autowired
    private INotificationService notificationService;

    @Override
    @Transactional
    public boolean joinClub(Long userId, Long clubId) {
        Club club = clubService.getById(clubId);
        if (club == null) {
            throw new BusinessException("俱乐部不存在");
        }

        // 检查是否已经是成员
        ClubMember existing = getOne(new LambdaQueryWrapper<ClubMember>()
                .eq(ClubMember::getUserId, userId)
                .eq(ClubMember::getClubId, clubId));

        if (existing != null && "active".equals(existing.getStatus())) {
            throw new BusinessException("您已经是该俱乐部成员");
        }

        // 检查俱乐部是否已满
        if (club.getCurrentMembers() >= club.getMaxMembers()) {
            throw new BusinessException("俱乐部已满员");
        }

        // 检查是否需要审核
        String status = Boolean.TRUE.equals(club.getNeedApproval()) ? "pending" : "active";

        ClubMember member;
        if (existing != null) {
            // 更新现有记录
            existing.setStatus(status);
            existing.setRole("member");
            updateById(existing);
            member = existing;
        } else {
            // 创建新记录
            member = new ClubMember();
            member.setClubId(clubId);
            member.setUserId(userId);
            member.setRole("member");
            member.setStatus(status);
            member.setEventsParticipated(0);
            member.setContributionPoints(0);
            save(member);
        }

        // 如果不需要审核，直接处理加入逻辑
        if ("active".equals(status)) {
            // 增加俱乐部成员数
            club.setCurrentMembers(club.getCurrentMembers() + 1);
            clubService.updateById(club);

            // 奖励用户积分
            pointsService.awardClubPoints(userId, clubId, "join");

            log.info("用户成功加入俱乐部: userId={}, clubId={}", userId, clubId);
        } else {
            log.info("用户申请加入俱乐部（待审核）: userId={}, clubId={}", userId, clubId);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean leaveClub(Long userId, Long clubId) {
        ClubMember member = getOne(new LambdaQueryWrapper<ClubMember>()
                .eq(ClubMember::getUserId, userId)
                .eq(ClubMember::getClubId, clubId)
                .eq(ClubMember::getStatus, "active"));

        if (member == null) {
            throw new BusinessException("您不是该俱乐部成员");
        }

        // 检查是否是创建者
        Club club = clubService.getById(clubId);
        if (club.getCreatorId().equals(userId)) {
            throw new BusinessException("俱乐部创建者不能退出，请先转让俱乐部");
        }

        // 更新状态为已退出
        member.setStatus("left");
        updateById(member);

        // 减少俱乐部成员数
        club.setCurrentMembers(club.getCurrentMembers() - 1);
        clubService.updateById(club);

        log.info("用户退出俱乐部: userId={}, clubId={}", userId, clubId);
        return true;
    }

    @Override
    @Transactional
    public boolean approveJoinRequest(Long memberId, Boolean approved, Long operatorId) {
        ClubMember member = getById(memberId);
        if (member == null || !"pending".equals(member.getStatus())) {
            throw new BusinessException("无效的申请记录");
        }

        // 检查操作者权限
        if (!isAdmin(operatorId, member.getClubId())) {
            throw new BusinessException("您没有权限审核申请");
        }

        if (Boolean.TRUE.equals(approved)) {
            // 通过申请
            member.setStatus("active");
            updateById(member);

            // 增加俱乐部成员数
            Club club = clubService.getById(member.getClubId());
            club.setCurrentMembers(club.getCurrentMembers() + 1);
            clubService.updateById(club);

            // 奖励用户积分
            pointsService.awardClubPoints(member.getUserId(), member.getClubId(), "join");

            // 发送通知
            notificationService.createInAppNotification(
                    member.getUserId(),
                    "加入俱乐部申请已通过",
                    "恭喜您，您的俱乐部加入申请已通过！",
                    "club_join_approved",
                    member.getClubId(),
                    "club"
            );

            log.info("俱乐部加入申请已通过: memberId={}, operatorId={}", memberId, operatorId);
        } else {
            // 拒绝申请
            member.setStatus("rejected");
            updateById(member);

            // 发送通知
            notificationService.createInAppNotification(
                    member.getUserId(),
                    "加入俱乐部申请未通过",
                    "很抱歉，您的俱乐部加入申请未通过。",
                    "club_join_rejected",
                    member.getClubId(),
                    "club"
            );

            log.info("俱乐部加入申请已拒绝: memberId={}, operatorId={}", memberId, operatorId);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean removeMember(Long memberId, Long clubId, Long operatorId) {
        ClubMember member = getById(memberId);
        if (member == null || !member.getClubId().equals(clubId)) {
            throw new BusinessException("成员不存在");
        }

        // 检查操作者权限
        if (!isAdmin(operatorId, clubId)) {
            throw new BusinessException("您没有权限移除成员");
        }

        // 不能移除创建者
        Club club = clubService.getById(clubId);
        if (club.getCreatorId().equals(member.getUserId())) {
            throw new BusinessException("不能移除俱乐部创建者");
        }

        // 更新状态
        member.setStatus("removed");
        updateById(member);

        // 减少俱乐部成员数
        if ("active".equals(member.getStatus())) {
            club.setCurrentMembers(club.getCurrentMembers() - 1);
            clubService.updateById(club);
        }

        // 发送通知
        notificationService.createInAppNotification(
                member.getUserId(),
                "您已被移出俱乐部",
                "您已被管理员移出俱乐部。",
                "club_removed",
                clubId,
                "club"
        );

        log.info("成员被移出俱乐部: memberId={}, operatorId={}", memberId, operatorId);
        return true;
    }

    @Override
    @Transactional
    public boolean setMemberRole(Long memberId, String role, Long operatorId) {
        ClubMember member = getById(memberId);
        if (member == null) {
            throw new BusinessException("成员不存在");
        }

        // 检查操作者权限（只有创建者可以设置角色）
        Club club = clubService.getById(member.getClubId());
        if (!club.getCreatorId().equals(operatorId)) {
            throw new BusinessException("只有俱乐部创建者可以设置成员角色");
        }

        // 更新角色
        member.setRole(role);
        updateById(member);

        log.info("成员角色已更新: memberId={}, newRole={}, operatorId={}", memberId, role, operatorId);
        return true;
    }

    @Override
    public List<ClubMember> getClubMembers(Long clubId, String status) {
        LambdaQueryWrapper<ClubMember> query = new LambdaQueryWrapper<ClubMember>()
                .eq(ClubMember::getClubId, clubId)
                .orderByDesc(ClubMember::getJoinedAt);

        if (status != null && !status.isEmpty()) {
            query.eq(ClubMember::getStatus, status);
        }

        return list(query);
    }

    @Override
    public boolean isMember(Long userId, Long clubId) {
        ClubMember member = getOne(new LambdaQueryWrapper<ClubMember>()
                .eq(ClubMember::getUserId, userId)
                .eq(ClubMember::getClubId, clubId)
                .eq(ClubMember::getStatus, "active"));

        return member != null;
    }

    @Override
    public boolean isAdmin(Long userId, Long clubId) {
        ClubMember member = getOne(new LambdaQueryWrapper<ClubMember>()
                .eq(ClubMember::getUserId, userId)
                .eq(ClubMember::getClubId, clubId)
                .eq(ClubMember::getStatus, "active"));

        if (member == null) {
            return false;
        }

        // 检查是否是管理员或创建者
        return "admin".equals(member.getRole()) || "owner".equals(member.getRole());
    }

    @Override
    @Transactional
    public boolean addContributionPoints(Long userId, Long clubId, Integer points) {
        ClubMember member = getOne(new LambdaQueryWrapper<ClubMember>()
                .eq(ClubMember::getUserId, userId)
                .eq(ClubMember::getClubId, clubId)
                .eq(ClubMember::getStatus, "active"));

        if (member == null) {
            return false;
        }

        member.setContributionPoints(member.getContributionPoints() + points);
        return updateById(member);
    }

    @Override
    public String getMemberRole(Long userId, Long clubId) {
        ClubMember member = getOne(new LambdaQueryWrapper<ClubMember>()
                .eq(ClubMember::getUserId, userId)
                .eq(ClubMember::getClubId, clubId)
                .eq(ClubMember::getStatus, "active"));

        return member != null ? member.getRole() : null;
    }
}
